package com.yanyilu.qiubite.controller;

import com.yanyilu.qiubite.entity.AdminUser;
import com.yanyilu.qiubite.entity.User;
import com.yanyilu.qiubite.jwt.Audience;
import com.yanyilu.qiubite.jwt.JwtIgnore;
import com.yanyilu.qiubite.service.AdminUserService;
import com.yanyilu.qiubite.service.UserService;
import com.yanyilu.qiubite.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    Audience audience;

    @Autowired
    AdminUserService adminUserService;


    /**
     * 管理端用户列表
     * @param pageNum
     * @param pageSize
     * @param phoneNumber
     * @param prizeCode
     * @param userName
     * @return
     */
    @RequestMapping("/admin/list")
    public R userList(@RequestParam("page") Integer pageNum,
                      @RequestParam("limit") Integer pageSize,
                      @RequestParam(value = "phoneNumber",required = false) String phoneNumber,
                      @RequestParam(value = "prizeCode",required = false) String prizeCode,
                      @RequestParam(value = "userName",required = false) String userName){

        String role = ParseJwtUtil.getRole(audience);
        Integer adminUserId = ParseJwtUtil.getUserId();

        if("1".equals(role)){

            /************************************************************/
            Pageable pagesable = PageUtil.pagelimit(pageNum, pageSize);
            AdminUser adminUser = adminUserService.findUserById(adminUserId);

            User user = new User();

            user.setSpotId(adminUser.getSpotId());
            user.setTaskCount(null);

            if(null != phoneNumber && phoneNumber.trim().length() != 0){
                user.setPhoneNumber(phoneNumber);
            }

            if(null != prizeCode && prizeCode.trim().length() != 0){
                user.setPrizeCode(prizeCode);
            }

            if(null != userName && userName.trim().length() != 0 ){
                user.setUserName(userName);
            }

            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("userName", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("prizeCode", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("phoneNumber", ExampleMatcher.GenericPropertyMatchers.contains());

            Example<User> example = Example.of(user,matcher);
            Page<User> pages = userService.spotUserList(example,pagesable);

            return R.ok().put("list",pages.getContent()).put("totalPages", pages.getTotalPages()).put("count", pages.getTotalElements());
            /****************************************************************/

        }else if("0".equals(role)){

            Pageable pagesable = PageUtil.pagelimit(pageNum, pageSize);

            User user = new User();
            user.setTaskCount(null);
            if(null != phoneNumber && phoneNumber.trim().length() != 0){
                user.setPhoneNumber(phoneNumber);
            }

            if(null != prizeCode && prizeCode.trim().length() != 0){
                user.setPrizeCode(prizeCode);
            }

            if(null != userName && userName.trim().length() != 0 ){
                user.setUserName(userName);
            }

            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("userName", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("prizeCode", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("phoneNumber", ExampleMatcher.GenericPropertyMatchers.contains());

            Example<User> example = Example.of(user,matcher);
            Page<User> pages = userService.spotUserList(example,pagesable);
            return R.ok().put("list",pages.getContent()).put("totalPages", pages.getTotalPages()).put("count", pages.getTotalElements());

        } else {
            return R.ok(ResultCode.NO_ROLE_ERROR);
        }
    }

    /**
     * 某景区兑奖记录列表
     * @param pageNum
     * @param pageSize
     * @param prizeCode
     * @return
     */
    @RequestMapping("/admin/pirzelist")
    public R pirzeList(@RequestParam("page") Integer pageNum,
                      @RequestParam("limit") Integer pageSize,
                       @RequestParam(value = "prizeCode",required = false) String prizeCode){

        String role = ParseJwtUtil.getRole(audience);
        Integer adminUserId = ParseJwtUtil.getUserId();

        if("1".equals(role) || "2".equals(role)){

            /************************************************************/
            Pageable pagesable = PageUtil.pagelimit(pageNum, pageSize);
            AdminUser adminUser = adminUserService.findUserById(adminUserId);

            User user = new User();

            user.setSpotId(adminUser.getSpotId());
            user.setState(0);
            if(null != prizeCode){
                user.setPrizeCode(prizeCode);
            };

            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("prizeCode", ExampleMatcher.GenericPropertyMatchers.contains());

            Example<User> example = Example.of(user,matcher);
            Page<User> pages = userService.spotUserList(example,pagesable);
            return R.ok().put("list",pages.getContent()).put("totalPages", pages.getTotalPages()).put("count", pages.getTotalElements());
            /****************************************************************/

        }else if("0".equals(role)){

            Pageable pagesable = PageUtil.pagelimit(pageNum, pageSize);

            User user = new User();

            user.setState(0);
            if(null != prizeCode){
                user.setPrizeCode(prizeCode);
            }

            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("prizeCode", ExampleMatcher.GenericPropertyMatchers.contains());

            Example<User> example = Example.of(user,matcher);
            Page<User> pages = userService.spotUserList(example,pagesable);
            return R.ok().put("list",pages.getContent()).put("totalPages", pages.getTotalPages()).put("count", pages.getTotalElements());

        } else {
            return R.ok(ResultCode.NO_ROLE_ERROR);
        }
    }

    /**
     * 兑奖查询接口
     * @param prizeCode
     * @return
     */
    @RequestMapping("/admin/search")
    public R search(@RequestParam("prizeCode")String prizeCode){

        User user = userService.prizeCodeByUser(prizeCode);
        return R.ok().put("user",user);
    }

    /**
     * 修改兑奖码使用状态
     * 未使用：0
     * 已使用：1
     * @param userId
     * @param prizeState
     * @return
     */
    @RequestMapping("/admin/update")
    public R update(@RequestParam("userId")Integer userId,
                    @RequestParam("prizeState")Integer prizeState){

        User user = userService.findById(userId);

        user.setPrizeState(prizeState);
        return userService.saveUserAndGift(user);
    }

//    userDelete

    /**
     * 清除用户信息
     * @param userId
     * @return
     */
    @RequestMapping("/admin/delete")
    public R deleteUser(@RequestParam("userId")Integer userId){

        String role = ParseJwtUtil.getRole(audience);
        if("0".equals(role)){
            return userService.userDelete(userId);
        }else {
            return R.ok(ResultCode.NO_ROLE_ERROR);
        }
    }


    /**
     * 保存用户信息
     * @param user
     * @return
     */
    @JwtIgnore
    @RequestMapping("save")
    public R saveUser(@RequestBody User user){
        user = userService.saveUser(user);
        if(null != user.getUserId()){
            String token = JwtTokenUtil.createJWT(user.getUserId().toString(), user.getUserName(), "role", audience);
            return R.ok().put("token", token);
        }else{
            return R.error("验证码错误或已过期");
        }
    }


    //获取配置
    @RequestMapping("getconfig")
    public R getWeixinConfig(@RequestParam("url")String url){
        //System.out.println(url);
        Integer userid = ParseJwtUtil.getUserId();
        return userService.getConfig(userid,url);
    }

    //生成兑换码
    @RequestMapping("/frontend/createcode")
    public R createPrizeCode(){
        Integer userId = ParseJwtUtil.getUserId();
        return userService.createPrizeCode(userId);
    }

}
